//
//  CYCallRecordCVCell.m
//  CreditAddressBook
//
//  Created by Lee on 15/5/22.
//  Copyright (c) 2015年 Lee. All rights reserved.
//

#import "CYCallRecordCVCell.h"
#import "CYCallRecord.h"
#import "UIImageView+WebCache.h"
#import "CYABTool.h"
#import "CYEscape.h"
#import "CYDialTool.h"
#import "CYJsonInfo.h"
#import "NSObject+MJKeyValue.h"


@interface CYCallRecordCVCell ()

@property (weak, nonatomic) IBOutlet UILabel *phoneLab;
@property (weak, nonatomic) IBOutlet UIImageView *headImageView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UIView *timeView;
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
//@property (weak, nonatomic) IBOutlet UIImageView *timesImageView;
//@property (weak, nonatomic) IBOutlet UILabel *timesLabel;
@property (weak, nonatomic) IBOutlet UIButton *detailBtn;
//@property (weak, nonatomic) IBOutlet UILabel *phoneLabel;
@property (weak, nonatomic) IBOutlet UIButton *detailBtnB;
@property (weak, nonatomic) IBOutlet UIImageView *icon;

@property (strong, nonatomic) UILongPressGestureRecognizer *longPress;

@property (nonatomic , assign) BOOL hasSetCorner;

@end

@implementation CYCallRecordCVCell

- (UILongPressGestureRecognizer *)longPress {
    if (!_longPress) {
        _longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    }
    return _longPress;
}

- (void)setStyle:(CYCallRecordCellStyle)style {
    _style = style;
    //        [CYHttpTool postWithURL:[CYURL shared].getCreditLevelByPhone params:@{@"phone":_callHistory[i]} success:^(id json) {
    //            CYLog(@"json = %@",json);
    //            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
    //            if (jsonInfo.isSuccess) {
    //            }
    //        } failure:^(NSError *error) {
    //
    //        }];
    //        
    //    }

    self.headImageView.layer.borderColor = [UIColor clearColor].CGColor;
    if (style == CYCallRecordCellStyleAdd) {
        self.nameLabel.hidden = YES;
        self.timeView.hidden = YES;
        self.timeLabel.hidden = YES;
        self.icon.hidden = YES;
        
//        self.timesImageView.hidden = YES;
//        self.timesLabel.hidden = YES;
        self.detailBtn.hidden = YES;
//        self.phoneLabel.hidden = YES;
        [self.headImageView setImage:[UIImage imageNamed:@"icon_add"]];
    } else {
        self.nameLabel.hidden = NO;
        self.timeView.hidden = NO;
        self.timeLabel.hidden = NO;
//        self.timesImageView.hidden = NO;
//        self.timesLabel.hidden = NO;
        self.detailBtn.hidden = NO;
        //        self.phoneLabel.hidden = YES;
        self.icon.hidden = NO;
    }
}

- (void)setCallRecord:(CYCallRecord *)callRecord {
    _callRecord = callRecord;
    [self.headImageView setImage:[UIImage imageNamed:@"ic_contact_info_header"]];
    if (callRecord.callHistory) {
//        self.phoneLabel.text = callRecord.callHistory.phone;
        if (callRecord.callHistory.name && ![callRecord.callHistory.name isEqualToString:@""]) {
            self.nameLabel.text = callRecord.callHistory.name;
            self.phoneLab.text = callRecord.callHistory.phone;
            
            if (callRecord.thumbnailLocal) {
                self.headImageView.image = callRecord.thumbnailLocal;
            } else {
                [self imageFromServiceWithName:self.nameLabel.text];
            }
        } else {
            self.nameLabel.text = callRecord.callHistory.phone;
            if (!callRecord.callHistory.headImageName) {
                [self imageFromLocal];
            } else {
                [self.headImageView setImage:[UIImage imageNamed:callRecord.callHistory.headImageName]];
            }
        }
        
        if (callRecord.showTimeView) {//最近一次通话或者通话时长
            if (![callRecord.newlyCallDate isEqualToString:@""]) {//最近一次通话
                self.timeLabel.text = callRecord.newlyCallDate;
            }else {//通话时长
                self.timeLabel.text = callRecord.callDurationSum1;
            }
            self.timeView.hidden = NO;
        } else {
            self.timeView.hidden = YES;
            self.timeLabel.text = @"";
        }
        //通话次数
//        self.timesImageView.hidden = !callRecord.showTimesImageView;
        if (callRecord.showTimesImageView) {
//            self.timesLabel.text = callRecord.times;
            self.icon.hidden = NO;
            self.timeLabel.hidden = NO;
            self.timeView.hidden = NO;
            self.timeLabel.text = callRecord.times;
        } else {
//            self.timesLabel.text = @"";
        }
    } else if (callRecord.person) {
        self.nameLabel.text = callRecord.person.name;
        if (callRecord.person.person.thumbnail) {
            self.headImageView.image = callRecord.person.person.thumbnail;
        }
    }
    
    //通讯录数据
    if (callRecord.dataType == CYCallRecordTypeABData) {
//        self.timesImageView.hidden = YES;
//        self.timeView.backgroundColor = [UIColor clearColor];
        self.timeLabel.text = @"详情";
        self.icon.hidden = YES;
//        self.timeView.hidden = YES;
//        self.timesLabel.text = @"";
    } else if (callRecord.dataType == CYCallRecordTypeCollectionData) {//收藏数据
        self.icon.hidden = YES;
        self.timeLabel.hidden = NO;
        self.timeView.hidden = NO;
        self.timeLabel.text = @"查看详情";
        self.phoneLab.hidden = YES;
        [self setupImageViewBorder];
    } else {
        
    }
    
    //添加tag
    self.detailBtn.tag = callRecord.indexPath.row;
    
    if (!self.hasSetCorner && callRecord.dataType != CYCallRecordTypeCollectionData) {
        [self setupImageViewBorder];
    }
}

/**
 *  随机匹配头像
 */
- (void)imageFromServiceWithName:(NSString *)name {
    CYPerson *cyperson = self.callRecord.person;
    if (cyperson && cyperson.person && !cyperson.person.thumbnail) {
        [CYABTool imageSelectOneWithParams:@{@"name": [CYEscape escapeWithString:name]} success:^(NSArray *defrs) {
            if (self.callRecord.callHistory.headImageName || self.callRecord.person.person.thumbnail) return;
            [self.headImageView sd_setImageWithURL:[NSURL URLWithString:defrs.firstObject] placeholderImage:[UIImage imageNamed:@"ic_contact_info_header"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                //保存图片到本地
                RHPerson *person = self.callRecord.person.person;
                if (!person.thumbnail) {
                    [person setImage:image];
                    [person save];
                }
            }];
            
        } failure:^(NSError *error) {
            
        }];
    }
}

- (void)imageFromLocal {
    int a = [CYDialTool randomNumForm:1 to:28];
    NSString *imageName = CYStringFormat(@"animol%d", a);
    UIImage *image = [UIImage imageNamed:imageName];
    self.callRecord.callHistory.headImageName = imageName;
    [self.headImageView setImage:image];
    [self.callRecord.callHistory update];
}

- (void)setupImageViewBorder {
    self.headImageView.layer.borderWidth = 2;
    self.headImageView.layer.borderColor = CYNaviThemeColor.CGColor;
    if (self.cellH) {
        self.headImageView.layer.cornerRadius = 25;
    } else {
        self.headImageView.layer.cornerRadius = 25;
    }
    self.headImageView.layer.masksToBounds = YES;
    self.hasSetCorner = YES;
}

/**
 *  注册cell
 *
 *  @param collectionview
 *  @param identifier
 */
+ (void)collectionView:(UICollectionView *)collectionview registerCellWithReuseIdentifier:(NSString *)identifier {
    [collectionview registerNib:[UINib nibWithNibName:@"CYCallRecordCVCell" bundle:nil] forCellWithReuseIdentifier:identifier];
}

/**
 *  创建cell
 *
 *  @param collectionview
 *  @param identifier
 *  @param indexPath
 *
 *  @return
 */
+ (instancetype)collectionView:(UICollectionView *)collectionview dequeueReusableCellWithReuseIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath {
    CYCallRecordCVCell *cell = [collectionview dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    return cell;
}

/**
 *  头部点击
 */
- (void)detailBtnAddTarget:(id)target action:(SEL)action {
    [self.detailBtn addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
    [self.detailBtnB addTarget:target action:action forControlEvents:UIControlEventTouchUpInside];
}

/**
 *  长按事件
 */
- (void)longPress:(UILongPressGestureRecognizer *)longPress {
    if(longPress.state == UIGestureRecognizerStateBegan) {
        CYAlertView(@"aa");
    }
}

- (void)awakeFromNib {
    [CYNotificationCenter addObserver:self selector:@selector(headImageChange:) name:CYAddressBookChangeNotification object:nil];
    
//    self.headImageView.userInteractionEnabled = YES;
//    [self.headImageView addGestureRecognizer:self.longPress];
    [self setupImageViewBorder];
}

- (void)headImageChange:(NSNotification *)noti {
    NSString *url = noti.userInfo[CYAddressBookImageKey];
    NSString *phone = noti.userInfo[CYAddressBookPhoneKey];
    if (CYStringEqualTo(self.callRecord.person.phone, phone)) {
        [self.headImageView sd_setImageWithURL:[NSURL URLWithString:url]];
    }
}

- (IBAction)detailBtn:(UIButton *)sender {
    
}

- (void)dealloc {
    [CYNotificationCenter removeObserver:self];
}

@end
